<template>
  <div class="inheritor-list">
    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <div class="search-box">
        <input
            v-model="searchQuery"
            placeholder="搜索传承人..."
            @input="filterInheritors"
        />

        <button @click="filterInheritors">
          搜索
          <i class="fas fa-search"></i>
        </button>
      </div>
      <div class="category-filter">
        <select v-model="selectedCategory" @change="filterInheritors">
          <option value="">所有类别</option>
          <option v-for="category in categories" :key="category.id" :value="category.id">
            {{ category.name }}
          </option>
        </select>
      </div>
    </div>
    <!-- 传承人列表 -->
    <div class="inheritor-grid">
      <InheritorCard
          v-for="inheritor in paginatedInheritors"
          :key="inheritor.id"
          :inheritor="inheritor"
          @click.native="goToDetail(inheritor.id)"
      />
    </div>

    <!-- 分页控制 -->
    <div class="pagination" v-if="totalPages > 1">
      <button
          v-for="page in totalPages"
          :key="page"
          :class="{ active: currentPage === page }"
          @click="changePage(page)"
      >
        {{ page }}
      </button>
    </div>
  </div>
</template>

<script>
import InheritorCard from '../views/InheritorCard.vue'
import { fetchInheritors } from '@/api/inheritorApi.js'
import image1 from "@/assets/1min.jpg";
import image2 from "@/assets/2yin.jpg";
import image3 from "@/assets/3wudao.jpg";
import image4 from "@/assets/4xiju.jpg";
import image5 from "@/assets/5quyi.jpg";
import image6 from "@/assets/6zaji.jpg";
import image7 from "@/assets/7meishu.jpg";
import image8 from "@/assets/8jiyi.jpg";
import image9 from "@/assets/9yiyap.jpg";
import image10 from "@/assets/10minsu.jpg";

export default {
  name: 'InheritorListView',
  components: {
    InheritorCard
  },
  data() {
    return {
      allInheritors: [],
      filteredInheritors: [],
      searchQuery: '',
      selectedCategory: '',
      categories: [

        { id: 'folk-literature', name: '民间文学'},
        { id: 'traditional-music', name: '传统音乐'},
        { id: 'traditional-dance', name: '传统舞蹈'},
        { id: 'traditional-drama', name: '传统戏剧'},
        { id: 'quyi', name: '曲艺',},
        { id: 'traditional-sports', name: '传统体育'},
        { id: 'recreation-acrobatics', name: '游艺与杂技'},
        { id: 'traditional-art', name: '传统美术'},
        { id: 'traditional-craft', name: '传统技艺'},
        { id: 'traditional-medicine', name: '传统医药'},
        { id: 'folk-custom', name: '民俗' }
      ],
      currentPage: 1,
      itemsPerPage: 12
    }
  },
  async created() {
    try {
      const response = await fetchInheritors();
      // 确保数据格式标准化
      console.log("API Response:", response); // 打印后端返回的数据
      this.allInheritors = Array.isArray(response) ? response : [];
      this.filteredInheritors = [...this.allInheritors];
    } catch (error) {
      console.error("加载数据失败:", error);
      this.allInheritors = [];
      this.filteredInheritors = [];
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.filteredInheritors.length / this.itemsPerPage);
    },
    paginatedInheritors() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredInheritors.slice(start, end);
    }
  },
  methods: {
    filterInheritors() {
      let result = this.allInheritors;

      // 按搜索词过滤（支持名字、描述）
      if (this.searchQuery) {
        const query = this.searchQuery.trim().toLowerCase();
        result = result.filter(inheritor =>
            inheritor.name.toLowerCase().includes(query) ||
            inheritor.description?.toLowerCase().includes(query)
        );
      }

      // 按类别过滤（category 是英文 ID）
      if (this.selectedCategory) {
        result = result.filter(inheritor =>
            inheritor.category === this.selectedCategory
        );
      }

      // ✅ 不管是否筛选，都更新 filteredInheritors
      this.filteredInheritors = result;
      this.currentPage = 1;
    },



    changePage(page) {
      this.currentPage = page
      window.scrollTo(0, 0)
    },
    goToDetail(id) {
      this.$router.push(`/inheritor/${id}`)
    }
  }
}
</script>

<style scoped>
.inheritor-list {

  padding-top: 60px;
  max-width: 1200px;
  margin: 0 auto;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.search-box {
  display: flex;
  width: 60%;
}

.search-box input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}

.search-box button {
  padding: 10px 15px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.category-filter select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.inheritor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.pagination {
  display: flex;
  justify-content: center;
  gap: 5px;
  margin-top: 30px;
}

.pagination button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
}

.pagination button.active {
  background: #42b983;
  color: white;
  border-color: #42b983;
}
</style>